package br.com.rampage.controller.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.rampage.model.bean.Paciente;
import br.com.rampage.model.bo.PacienteBO;
import br.com.rampage.utils.AppUtils;

@WebServlet("/LoginAplicacao")
public class LoginAplicacaoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public LoginAplicacaoServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String user = request.getParameter("user");
		String password = request.getParameter("password");
		Paciente p = new PacienteBO().carregar(user);
		
		if (p != null && p.getSenha().equals(password)) {
			
			RequestDispatcher dispatcher = request.getRequestDispatcher("/preview_aplicacao.jsp");
			AppUtils.getInstace().setPacienteSelecionado(p);
			dispatcher.forward(request, response);
		} else {
			erroLogin(request, response);
		}
	}

	private void erroLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		response.setContentType("text/html;charset-UTF-8");
		PrintWriter writer = response.getWriter();
		new Message().print(writer, TypeReturnServlet.danger,"Login/Senha incorreto!");

		RequestDispatcher dispatcher = request.getRequestDispatcher("/system.jsp");
		dispatcher.include(request, response);
	}
}
